package utils;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    private static String URL;
    private static String USER;
    private static String PASSWORD;
    private static String DRIVER;

    static {
        try {
            Properties pro = new Properties();
            //ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            //URL res = classLoader.getResource("src/jdbc.properties");
            //String path = res.getPath();
            //System.out.println(path);
            //path = java.net.URLDecoder.decode(path);
            //System.out.println(path);
            //pro.load(new FileReader(path));
            pro.load(new FileReader("D:\\code\\idea_projects\\dpd_rule-based\\src\\jdbc.properties"));
            URL = pro.getProperty("url");
            USER = pro.getProperty("user");
            PASSWORD = pro.getProperty("password");
            DRIVER = pro.getProperty("driver");
            Class.forName(DRIVER);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static int getRow(ResultSet rs) throws SQLException {
        int counter = 0;
        rs.beforeFirst();    //将光标移动到此 ResultSet 对象的开头，正好位于第一行之前
        while (rs.next()) {
            counter++;
        }
        return counter;
    }
}
